<?php

require_once 'jujucock.php';
require_once 'optparse.php';

define('PORT', 54344);

$opt_parser = new OptionParser();
$opt_parser->addOption('', '--noisy', 'noisy', 'show noisy information', 'bool');
try {
	list($options, $args) = $opt_parser->parse( $argv );
}
catch(Exception $ex) {
	echo 'Exception: ',$ex->getMessage(),"\n";
	exit(2);
}

$noisy = false;
if (isset($options['noisy'])) {
    $noisy = $options['noisy'];
}

///////////////////////////////////////////////////////////////////////

$sock = socket_create_listen(PORT);
if (false === $sock) {
    echo 'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
    exit (1);
}
$ok = socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1);
if (!$ok) {
    echo 'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
    exit (1);
}

socket_getsockname($sock, $addr, $port);
print "Server Listening on $addr:$port\n";

while($c = socket_accept($sock)) {
    socket_getpeername($c, $raddr, $rport);
    print "Received Connection from $raddr:$rport\n";
    var_dump($c);
    $channel = new JuTCPChannel($c);
       
    while( true ) {
       /* do something useful */
       $buf = '';
       $buf_length = 32;
       try {
           $length = $channel->recv($buf);
       }
       catch(Exception $ex) {
           printf("RECV Exception:%s\n", $ex->getMessage());
           break;
       }
       //if ($noisy) {
       //    echo 'RECV: >>>',$buf,"<<<\n";
       //}
       $packet = depack($buf);
       $packet->respid = $packet->packid;
       $packet->packid = 0;
       list($record, $packid) = enpack($packet);
       //if ($noisy) {
       //    echo 'BACK: >>>',$record,"<<<\n";
       //}
       try {
           $channel->send($record . "\n");
       }
       catch(Exception $ex) {
           printf("SEND Exception:%s\n", $ex->message);
           break;
       }
    }
    socket_close($c);
}

socket_close($sock); 
